<template>
    <div class="assement">
        <div class="base_header">
            <img src="../../assets/img/back.png" alt="" @click="goBack">发表评价
            <span class="fr f14" @click="publish()">发布</span>
        </div>
        <div class="goods-Info" v-for="(deliveryOrder,key) in orderDetail.deliveryOrders" :key="key">
            <div class="order-id">
                <span class="fr">{{orderDetail.receiveTime}}</span>
                 <span class="fl f14">订单号：{{deliveryOrder.deliveryOrderCode }}</span>
            </div>
            <div class="goods-detail" v-for="(product,key) in deliveryOrder.products" :key="key">
                <div class="detail fr">
                    <div class="price">
                        <span class="fr">￥{{product.price}}</span>
                        <span class="fl">{{product.name}}</span>   
                    </div> 
                    <div class="size">
                        <span class="fr">x{{product.quantity}}</span>
                        <span class="fl">{{product.spec}}</span>
                    </div>
                </div>
                <div class="fl goods-img">
                    <img :src="imageDomain+product.image" alt="">
                </div>
            </div>
        </div>
        <div class="goods-price" v-for="(deliveryOrder,key) in orderDetail.deliveryOrders" :key="key">
            <span class="fr" v-for="(product,key) in deliveryOrder.products" :key="key">
                数量：{{product.quantity}} 实付款：￥{{orderDetail.payAmount}}
            </span>
        </div>
        <div class="assements">
            <div class="f16 mt10 mb10">
                交易评价
            </div>
            <div class="progress">
                  <div v-for="(item,key,index0) in  assements" :key="key"> 
                     <span class="service">{{item.name}}</span>
                     <span class="stars" v-for="(item1,key1,index1) in 5" :key="key1" @click="getStar(key,key1)">
                         <img src="../../assets/img/order/star.png" alt=""  v-if="key1>item.value"> 
                         <img src="../../assets/img/order/star-active.png" alt="" v-else>
                    </span><span class="ml10">{{item.status[item.value]}}</span>
                 </div> 
            </div>
        </div>
        <div class="text-assement">
            <textarea name="" id="" placeholder="宝贝满足你的期待吗？说说他的优点和美中不足的地方吧" required v-model="content.desc"></textarea>
        </div>
        <div class="pictures">
            <div v-for=" (item,index) in imgurl">
                 <img :src="imgDomin+item" alt="" >
                 <span @click="click(index)">X</span>
            </div>
          
        </div>
        <div class="add-picture" @click="showActionSheet()">
            <div class="fl camer">
                <img src="../../assets/img/order/addPic.png" alt="">
            </div>
            <div class="fl words" >
                <span>上传图片</span>
                <span class="c999 small-font mt5">内容丰富的评价更容易引起关注哦</span>
            </div>
        </div>
        <div class="check">
            <span @click="checkStatus=!checkStatus" class="fl chose">
                 <img src="../../assets/img/order/radio.png" alt="" v-if="!checkStatus">
                <img src="../../assets/img/order/checked.png" alt="" v-else>
            </span> 
            <span class="tip">
                 <span class="f14">匿名评价</span>
                 <span class="f12 c999">匿名评价不会对外公开您的头像、昵称给其他用户和商家 </span>
            </span>
        </div>
    </div>
</template>

<style>
    @import url("./assement.css");
</style>
<script>
    import Layer from '../../assets/js/MessageBox'
    import API from '../../assets/js/API'
    import Validate from '../../assets/js/Validate'
    import { MessageBox } from 'mint-ui';

    export default {
        data() {
            return {
                assements:[
                    { 
                        name:'商品描述',
                        status:['非常差','差','好','很好','非常好'],
                        value:-1,
                    },
                     { 
                        name:'物流服务',
                        status:['非常差','差','好','很好','非常好'],
                        value:-1,
                    },
                     { 
                        name:'服务态度',
                        status:['非常差','差','好','很好','非常好'],
                        value:-1,
                     }
                ],
                checkStatus:false,
                deliveryOrderCode: this.$route.query.deliveryOrderCode,
                orderDetail:{deliveryOrders: [{deliveryOrderCode: ""}]},
                imageDomain:'',
                content:{
                    desc:'',
                    screenShot:'',
                    descScore:0,
                    serveScore:0,
                    expressScore: 0 
                },
                person:{},
                  imgurl:[],
               imgDomin: API.testYbAppraiserDomin,
               screenShot:''
            }
        },
        created() {
             window.scrollTo(0,0);
            let url = API.serviceDomain + API.orderDetail + "/" + this.deliveryOrderCode;
             let personurl = API.serviceDomain + API.personDetail;
             this.$http.get(url).then(
                 (res) =>{
                        if(res.body.status == '000000'){
                            this.orderDetail=res.body.data;
                        }else {
                              Layer.showMsg(res.body.message);
                         }
                 },
                 (error) => {
                    Layer.showMsg("服务器开小差了...")
                    return
                }
             );
             this.$http.get(personurl).then(
                (res) => {
                    if (res.body.status == '000000') {
                        this.person = res.body.data.userInfo;
                    } else {
                        Layer.showMsg(res.body.message);
                    }
                },
                (error) => {
                    Layer.showMsg("服务器开小差了...")
                    return
                }
            ) 
        },
        mounted(){
             this.imageDomain = API.imageDomain;
            let token = localStorage.getItem('token');
            if (!token) {
                Layer.showMsg("您还未登录!")
                ;
                this.$router.push({path: '/login'});
            }
           
        },
        computed:{
            getAssementData(){
                let form=new FormData()
                    this.screenShot=this.imgurl.join(',')
                    form.append('shopId',this.orderDetail.deliveryOrders[0].shopId)
                    form.append('orderId',this.deliveryOrderCode)
                    form.append('gId',this.orderDetail.deliveryOrders[0].products[0].productId)
                    form.append('avatar', this.person.headImg)
                    form.append('name',this.person.nickName)
                    form.append('desc',this.content.desc)
                    form.append('mobile',this.person.mobile)
                    form.append('isTor',this.checkStatus)
                    form.append('screenShot',this.screenShot)
                    form.append('descScore',this.assements[0].value+1)
                    form.append('serveScore',this.assements[0].value+1)
                    form.append('expressScore',this.assements[0].value+1)

                return form;
               
            }
        } ,
        methods: {
            goBack() {
                this.$router.goBack()
            },
            getStar(key,key1){
                if(key==0){
                    this.assements[0].value=key1;
                }else if(key==1){
                     this.assements[1].value=key1;
                }else{
                     this.assements[2].value=key1;
                }
            },
            click(index){
                this.imgurl.splice(index, 1)
            },
            publish(){
                let url=API.evaluate+API.addEvaluate
                if(this.assements[0].value==-1){
                     Layer.showMsg("请对商品描述进行评分！")
                }else if(this.assements[1].value==-1){
                     Layer.showMsg("请对物流服务进行评分！")
                }else if(this.assements[2].value==-1){
                     Layer.showMsg("请对服务态度进行评分！")
                }else if(this.content.desc==""){
                     Layer.showMsg("请填写您对商品的评价！")
                }else{
                        this.$http.post(url,this.getAssementData,
                        {
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                        }
                        ).then(
                        (res) => {
                            if (res.body.code==1) {
                               this.$router.push({path:'order',query:{orderType:''}})
                            } else {
                                Layer.showMsg(res.body.error)
                            }
                        },
                        (error) => {
                            Layer.showMsg("服务器开小差了...")
                            return
                        }
                    )
                }
            },
              getToken(url){
                    let form=new FormData()
                    console.log(API.testQiNiuUrl+API. ybAppraiseBucket)
                    this.$http.get(API.testQiNiuUrl+API. ybAppraiseBucket,{
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    })
                    .then(
                        (res)=>{
                            this.token=res.body.retMsg
                            this.uploadImg(res.body.retMsg,url)
                        }
                        )
            },
            uploadImg(token,new_file){
                let that=this
                let wt = plus.nativeUI.showWaiting();  
                let task = plus.uploader.createUpload("http://upload.qiniu.com", {
                    method: "POST"
            }, function(t, status) { //
                        let data = JSON.parse(t.responseText);
                        if (status == 200) {
                            that.imgurl.push(data.hash)
                            wt.close();
                        } else {
                            mui.toast("上传失败：" + status);
                            wt.close();
                        }
                    })
                    task.addFile(new_file, { key: "file" });
                    task.addData("token", token);//七牛所需参数
                    task.start();
            },
              showActionSheet() {   
                let that=this;
                    let bts = [{    
                        title: "拍照"    
                    }, {    
                        title: "从相册选择"    
                    }];    
                    plus.nativeUI.actionSheet({    
                            cancel: "取消",    
                            buttons: bts    
                        },    
                        function(e) {    
                            if (e.index == 1) {    
                                that.getImage();    
                            } else if (e.index == 2) {    
                                that.galleryImgs();    
                            }    
                        }    
                    );    
                },  
                //从相册选择照片  
            galleryImgs() {
                let that=this;
                    plus.gallery.pick(function(e) {    
                        let name = e.substr(e.lastIndexOf('/') + 1);  
                    that.compressImage(e,name);  
                    }, function(e) {    
                    }, {    
                        filter: "image"    
                    });    
                },
                //拍照
                getImage() {  
                    let that=this
                let cmr = plus.camera.getCamera();    
                cmr.captureImage(function(p) {    
                    plus.io.resolveLocalFileSystemURL(p, function(entry) {    
                        that.compressImage(entry.toLocalURL(),entry.name);    
                    }, function(e) {    
                        plus.nativeUI.toast("读取拍照文件错误：" + e.message);    
                    });    
                }, function(e) {    
                }, {    
                    filter: 'image'   
                });    
            },  
                //压缩图片    
            compressImage(url,filename){  
                    let that=this;
                let name="_doc/upload/"+filename;  
                plus.zip.compressImage({    
                        src:url,//src: (String 类型 )压缩转换原始图片的路径    
                        dst:name,//压缩转换目标图片的路径    
                        quality:40,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100    
                        overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件    
                    },    
                    function(zip) {  
                        //页面显示图片  
                        that.showPics(zip.target,name);  
                    },function(error) {    
                        plus.nativeUI.toast("压缩图片失败，请稍候再试");    
                });    
            },
            showPics(url,name){          
                //根据路径读取到文件   
                let that=this
                plus.io.resolveLocalFileSystemURL(url,function(entry){  
                    entry.file( function(file){  
                        let fileReader = new plus.io.FileReader();  
                        fileReader.readAsDataURL(file);  
                        fileReader.onloadend = function(e) {  
                                let picUrl= e.target.result.toString(); 
                                that.getToken(url )
                        }  
                    });  
                });   
            }  
        }
    }
</script>
